<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { PlusColumn } from 'plus-pro-components'

import { useAddScheme, useEditScheme, useSchemeInfo } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number | string>('id', { required: true })
const formRef = ref()

type Istate = {
    id: string
    name: string
}

const initialState = {
    id: '',
    name: '',
}
const state = ref<Istate>(cloneDeep(initialState))
const title = computed(() => {
    return id.value ? '编辑方案' : '新建方案'
})

const { isPending: addSchemePending, mutate } = useAddScheme()
const { isPending: editSchemePending, mutate: editSchemeMutate } = useEditScheme()
const { data: schemeInfo, isLoading: schemeInfoLoading } = useSchemeInfo(id)
const isPending = computed(() => {
    return addSchemePending.value || editSchemePending.value || schemeInfoLoading.value
})

watchEffect(() => {
    if (id.value) {
        if (schemeInfo.value) {
            state.value.id = schemeInfo.value.id
            state.value.name = schemeInfo.value.name
        }
    }
})

const columns: PlusColumn[] = [
    {
        label: '类目方案名称',
        prop: 'name',
    },
]

function validateCategoryName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入类目方案名称'))
    }
    if (pattern.test(value))
        callback(new Error('类目方案名称不允许输入空格'))

    else
        callback()
}

const rules = {
    name: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateCategoryName,
        },
    ],
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
        }
        console.log(params, 'params')
        const fn = id.value ? editSchemeMutate : mutate

        fn(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="600"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="schemeInfoLoading"
                    animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="120"
                  :rules="rules"
                  :has-footer="false"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
